﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH6_2006A.LowCode.Common
{
    public class FileHelper
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="formFiles">表单文件</param>
        /// <param name="folder">保存的文件夹</param>
        /// <param name="extension">扩展名判断</param>
        /// <returns>文件服务器所在路径</returns>
        public static async Task<Tuple<bool,string,List<string>>> FileUploadAsnyc(Microsoft.AspNetCore.Http.IFormFileCollection formFiles,string folder= "temporary", FileExtensionRule extension = 0)
        {
            if(formFiles == null || formFiles.Count<=0)
                return await Task.Run(()=> {  return Tuple.Create(false, "未选择文件", new List<string>()); });

            try
            {
                List<string> filePathList = new();
                foreach (var file in formFiles)
                {
                    #region 文件重名称
                    //获取扩展名（可以根据扩展名去判断上传文件的规则，可以单独定义枚举去判断）
                    var ext = Path.GetExtension(file.FileName); //可以打断点，去获知ext包不包括那个点

                    #region 文件格式验证

                    if (extension > 0) 
                    {
                        //就验证
                    }

                    #endregion

                    //用当前日期时间进行命名
                    var time = DateTime.Now.ToString("yyyyMMddHHmmss"); //20221130154954
                    var newFileName = time + ext;
                    #endregion

                    //创文件夹，拼接服务器路径
                    var path = $"wwwroot/{folder}/";
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    string filePath = Path.Combine(path, newFileName);

                    //将选择的文件保存到服务器上
                    //using (var stream = System.IO.File.OpenWrite(filePath))
                    using (var stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        await file.CopyToAsync(stream);
                        filePathList.Add(filePath);
                    }
                }

                return Tuple.Create(true, "上传成功", filePathList);
            }
            catch (Exception ex)
            {
                return await Task.Run(() => { return Tuple.Create(false, ex.Message, new List<string>()); });
            }
            
        }
    }

    public enum FileExtensionRule
    {
        //word,excel,pdf ...
        Document = 1,

        //jpg,jpeg,gif
        Image,

        //vidoe
        Video,

        //other:text,json ...
        Other
    }
}
